﻿using FrameWork.IService;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;

namespace FrameWork.Service
{
   public class SocketService : ISocketService
   {
       public ArraySegment<byte> ReceiveAndSend(string socketid, ArraySegment<byte> context)
       {
            var str = PublicTool.GetString(context.Array).Replace("\0", "");
            if (string.IsNullOrWhiteSpace(str)) return new ArraySegment<byte>();

            JObject json;
            try
            {
                json = JObject.Parse(str);
            }
            catch (Exception)
            {
                return new ArraySegment<byte>();
            }

            if (json == null) return new ArraySegment<byte>();

            var msgType = json["msgType"]?.ToString();

            if (string.IsNullOrWhiteSpace(msgType)) return new ArraySegment<byte>();

            if (msgType.Equals("registered"))
            {
                var dic = new Dictionary<string, string>
                {
                    { "msgType","linkUrl"},
                    { "text",$"{PublicTool.ApplicationHost}Home/Index/{socketid}"}
                };

                var bytes = PublicTool.GetBytes(JObject.FromObject(dic).ToString());
                return new ArraySegment<byte>(bytes);
            }

            return new ArraySegment<byte>();
        }
    }
}
